var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  var array = ['1', 'a', '2', 'b'];
  var jsonObj = {'sno': 1, 'sname': 'zhangsan'};
  var jsonArray = {1: {'sno': 2, 'sname': 'lisi'}, 2: {'sno': 3, 'sname': 'wangwu'}};
  res.render('index', { title: 'Express', array: array, jsonObj: jsonObj, jsonArray: jsonArray});
});

router.get('/send', function(req, res) {
  var amqp = require('amqplib/callback_api');
  amqp.connect('amqp://localhost', function(err, conn) {
    conn.createChannel(function(err, ch) {
      var q = 'hello';
      ch.assertQueue(q, {durable: false});
      ch.sendToQueue(q, new Buffer('Hello World!'));
      console.log(" [x] Sent 'Hello World!'");
      res.render('rabbitmq', { title: 'Send \'Hello World!\' Success'});
    });
    setTimeout(function() { conn.close(); process.exit(0) }, 500);
  });
});

router.get('/receive', function(req, res) {
  var amqp = require('amqplib/callback_api');
  amqp.connect('amqp://localhost', function(err, conn) {
    conn.createChannel(function(err, ch) {
      var q = 'hello';
      ch.assertQueue(q, {durable: false});
      console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
      ch.consume(q, function(msg) {
        console.log(" [x] Received %s", msg.content.toString());
        res.render('rabbitmq', { title: 'Receive ' + msg.content.toString() + ' Success'});
      }, {noAck: true});
    });
    setTimeout(function() { conn.close(); process.exit(0) }, 500);
  });
});

module.exports = router;
